package com.seanzx.dp.common;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Persist {
    public static File tableSchema() {
        String path = Persist.class.getClassLoader().getResource("").getPath();
        File file = new File(path + "/TABLE_SCHEMA");
        if (!file.exists()) {
            file.mkdir();
        }
        return file;
    }

    public static File properties() {
        String path = Persist.class.getClassLoader().getResource("").getPath();
        return new File(path).toPath().resolve("db.properties").toFile();
    }

    public static File getDatabase(String databaseName) {
        return Persist.tableSchema().toPath().resolve(databaseName).toFile();
    }

    public static List<String> showDatabases() {
        File[] files = Persist.tableSchema().listFiles();
        assert files != null;
        List<String> databases = new ArrayList<>(files.length);
        for (File file : files) {
            databases.add(file.getName());
        }
        return databases;
    }

    public static File getTable(String databaseName, String tableName) throws IOException {
        return getDatabase(databaseName).toPath().resolve(tableName + ".tbl").toFile();
    }

    public static byte[] getVarcharBytes(int length, String value) {
        length = length / 256 + 1;
        if (value == null) {
            byte[] resultBytes = new byte[length + 1];
            Arrays.fill(resultBytes, (byte) '\000');
            resultBytes[resultBytes.length - 2] = '\001';
            return resultBytes;
        }
        byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);
        byte[] resultBytes = new byte[valueBytes.length + length];
        int len = value.length();
        for (int i = 0; i < length; i++) {
            resultBytes[i] = (byte) (len % 256);
            len /= 256;
        }
        if (resultBytes.length - length >= 0) {
            System.arraycopy(valueBytes, 0, resultBytes, length, resultBytes.length - length);
        }
        return resultBytes;
    }
}
